<?php

namespace app\admin\controller\team;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use ReflectionFunction;
/**
 * 用户提现管理
 *
 * @icon fa fa-circle-o
 */
class Cashout extends Backend
{

    /**
     * Cashout模型对象
     * @var \app\admin\model\team\Cashout
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\team\Cashout;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $list = $this->model
                    ->where($where)
                    ->where('form',1)
                    ->order($sort, $order)
                    ->paginate($limit)->each(function($item,$key){
                        switch($item['type'])
                        {
                            case 1;
                                $item['type'] = '微信';
                                break;
                            case 2;
                                $item['type'] = '银行卡';
                                break;
                        }
                        switch($item['status'])
                        {
                            case 1;
                                $item['status'] = '待审核';
                                break;
                            case 2;
                                $item['status'] = '审核成功';
                                break;
                            case 3;
                                $item['status'] = '审核失败';
                                break;
                        }
                        // 团长：status：0：否，1：是；is_vip：0：否，1：是
                        $user = Db::name('user')->where('id',$item['user_id'])->field('status,is_vip')->find();
                        if($user['status'] = 1)
                        {
                            $item['is_status'] = "团长";
                        }else{
                            if($user['is_vip'] == 1)
                            {
                                $item['is_status'] = "会员";
                            }else{
                                $item['is_status'] = "非会员";
                            }
                        }

                        return $item;
                });

            $money  = $this->model->where($where)->where(['form'=>1])->sum('money');

            $result = array("total" => $list->total(), "rows" => $list->items(),"extend"=>['money'=>$money]);

            return json($result);
        }
        return $this->view->fetch();
    }

    /*
     * 审核状态  审核成功 金额到对应的账户
     * */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {

            $params = $this->request->param();
            if(empty($params['status']))$this->error(__('请选择审核状态'));
            if(Db::name('cashout')->where('id',$ids)->value('status') != 1)$this->error(__('已审核不能重复提交审核'));
            // 审核成功  金额提现到对应的 微信 或者 银行卡
            
            if($params['status'] == 2)
            {
                $data = ['status'=>$params['status'],'update_time'=>time()];
            }else{
                if(empty($request['content']))$this->error(__('请输入失败的理由'));
                $data = ['status'=>$params['status'],'update_time'=>time(),'content'=>$params['content']];
            }
            $user_id = Db::name('cashout')->where('id',$ids)->value('user_id');

            Db::startTrans();
            try{

                $data   = Db::name('cashout')->where(['status'=>1,'form'=>1,'id'=>$ids])->find();
                $openid = Db::name('user')->where('id',$user_id)->value('openid');
                
                $config = Config('wechat_pay');
                $param  = [];

                $metas = range(0, 9);
                $metas = array_merge($metas, range('A', 'Z'));
                $metas = array_merge($metas, range('a', 'z'));
                $noncestr = '';
                for ($i = 0; $i < 16; $i++) {
                    $noncestr .= $metas[rand(0, count($metas) - 1)];//生成签名的随机串
                }
                
                $appid  = $config['app_id'];//商户账号appid
                $mch_id = $config['mch_id'];//商户号
                $key    = $config['key'];
                
                $withdrawApply['batch_no']      =  'cs' . date("Ymd") . rand(10000, 90000) . rand(10000, 90000);
                $withdrawApply['left_money']    =  $data['money'];//金额
                $withdrawApply['sn']    = $noncestr;//随机字符串
                $userAuth['openid']     = $openid;
                $res = $this->transfer($withdrawApply,$userAuth,$config);
                
//                 $arr = array();
//                 $arr['mch_appid'] = $appid;
//                 $arr['mchid'] = $mch_id;
//                 $arr['nonce_str'] = $noncestr;//随机字符串，不长于32位
//                 $arr['partner_trade_no'] = '123456789' . date("Ymd") . rand(10000, 90000) . rand(10000, 90000);//商户订单号
//                 $arr['openid'] = $openid;
//                 $arr['check_name'] = 'NO_CHECK';//是否验证用户真实姓名，这里不验证
//                 $arr['amount'] = $data['money'] * 100;//付款金额，单位为分
//                 $arr['desc'] = "提现";//描述信息
// //        $arr['spbill_create_ip'] = 'xx.xx.xx.xx';//获取服务器的ip
//                 //封装的关于签名的算法
//                 $arr['sign'] = $this->makeSign($arr,$key);//签名
//                 $var = $this->arrayToXml($arr);
//                 // dump($arr['sign'] );exit;
//                 $xml = $this->curl_post_ssl('https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers',$var,30, array(), 1);
//                 libxml_disable_entity_loader(true);
//                 // echo $xml; die;
//                 $obj1=simplexml_load_string($xml,'SimpleXMLElement');
// // var_dump($obj1); die;
//                 $rdata = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)),true);
//                 // var_dump('cash_xmldata',$rdata);//eblog('cash_xmldata',$rdata);
//                 // dump($rdata);exit;
//                 print_r($rdata);exit;
//                 $return_code = trim(strtoupper($rdata['return_code']));
//                 $result_code = trim(strtoupper($rdata['result_code']));
                if($res['code'] == 200)
                {
                    $refund = [
                        'orderno' => $data['orderno'],
                        'money'   => $data['money'],
                        'pay_time'=> time(),
                        'status'  => 2,// 成功
                        'update_time'=> time()
                    ];
                    // 退款记录
                    Db::name('cashout')->where('id',$ids)->update($refund);
                } else {
                    // $returnmsg = $rdata['return_msg'];
                    // $err_code_des = $res['msg'];
                    $isrr = array(
                        'status' => 0,
                        'msg' => $res['msg'],
                    );
                }
                Db::commit();
                $this->success(__($isrr['msg']));
            }catch(Exception $exception){
                Db::rollback();
                $this->success(__('审核失败'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /*
     * 我的团队
     * */
    public function team()
    {
        
    }


    /*
    * 对要发送到微信统一下单接口的数据进行签名
    */
    protected function getSign($Obj, $key)
    {

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);

        $String = $this->formatBizQueryParaMap($Parameters, false);

        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . $key;
        //签名步骤三：MD5加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);

        return $result_;
    }


    /*
    *排序并格式化参数方法，签名时需要使用
    */
    protected function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = "";
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    /*
    * 生成随机字符串方法
    */
    protected function createNoncestr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    //数组转字符串方法
    protected function arrayToXm($arr)
    {

        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    protected static function xmlToArray($xml)
    {
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }

    //需要使用证书的请求
    private function postXmlSSLCurl($xml, $url, $second = 30)
    {

        $ch = curl_init();
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //设置证书
        //使用证书：cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
//        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
//        curl_setopt($ch, CURLOPT_SSLCERT, getcwd().'/apiclient_cert.pem');
//        //默认格式为PEM，可以注释
//        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
//        curl_setopt($ch, CURLOPT_SSLKEY, getcwd().'/apiclient_key.pem');

        curl_setopt($ch, CURLOPT_SSLCERT,getcwd().'/apiclient_cert.pem');
        curl_setopt($ch, CURLOPT_SSLKEY,getcwd().'/apiclient_key.pem');
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $data = curl_exec($ch);

        //返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error" . "<br>";
            curl_close($ch);
            return false;
        }
    }
    
    
    //  签名
    protected function makesign($data,$key)
    {
        //获取微信支付秘钥
        $data = array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a = http_build_query($data);
        $string_a = urldecode($string_a);
        //签名步骤二：在string后加入KEY
        //$config=$this->config;
        $string_sign_temp = $string_a."&key=".$key;
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $result = strtoupper($sign);
        // $result = strtoupper(hash_hmac("sha256",$string_sign_temp,$key));
        return $result;
    }
    //
    protected function arraytoxml($data){
        $str='<xml>';
        foreach($data as $k=>$v) {
            $str.='<'.$k.'>'.$v.'</'.$k.'>';
        }
        $str.='</xml>';
        return $str;
    }
    //
    protected function curl_post_ssl($url, $vars, $second = 30, $aHeader = array())
    {
        $isdir = "cert/";//APP_PATH."/common/library/php_sdk/lib/";//证书位置
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置执行最长秒数
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//
//        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');//证书类型
//        curl_setopt($ch, CURLOPT_SSLCERT, $isdir . 'apiclient_cert.pem');//证书位置
//        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');//CURLOPT_SSLKEY中规定的私钥的加密类型
//        curl_setopt($ch, CURLOPT_SSLKEY, $isdir . 'apiclient_key.pem');//证书位置
//        curl_setopt($ch, CURLOPT_CAINFO, 'PEM');
//        curl_setopt($ch, CURLOPT_CAINFO, $isdir . 'rootca.pem');

        curl_setopt($ch, CURLOPT_SSLCERT,getcwd().'/apiclient_cert.pem');
        curl_setopt($ch, CURLOPT_SSLKEY,getcwd().'/apiclient_key.pem');
        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);//设置头部
        }
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);//全部数据使用HTTP协议中的"POST"操作来发送
        $data = curl_exec($ch);//执行回话
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }
    
    
    
    
    
    /*------------------------微信转账到零钱-------------------------*/
    
    
    /**
     * @notes 商家转账到零钱
     */
    function transfer($withdrawApply,$userAuth,$config)
    {
        //请求URL
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        //请求方式
        $http_method = 'POST';
        //请求参数
        $data = [
            //申请商户号的appid或商户号绑定的appid（企业号corpid即为此appid）
            'appid'     => $config['app_id'],
            //商户系统内部的商家批次单号，要求此参数只能由数字、大小写字母组成，在商户系统内部唯一
            'out_batch_no' => $withdrawApply['batch_no'],
            //该笔批量转账的名称
            'batch_name' => '提现至微信零钱',
            //转账说明，UTF8编码，最多允许32个字符
            'batch_remark' => '提现至微信零钱',
            //转账金额单位为“分”。转账总金额必须与批次内所有明细转账金额之和保持一致，否则无法发起转账操作
            'total_amount' => $withdrawApply['left_money'] * 100,
            //一个转账批次单最多发起三千笔转账。转账总笔数必须与批次内所有明细之和保持一致，否则无法发起转账操作
            'total_num' => 1,
            'transfer_detail_list' => [
                [   //发起批量转账的明细列表，最多三千笔
                    //商户系统内部区分转账批次单下不同转账明细单的唯一标识，要求此参数只能由数字、大小写字母组成
                    'out_detail_no' => $withdrawApply['sn'],
                    //转账金额单位为分
                    'transfer_amount' => $withdrawApply['left_money'] * 100,
                    //单条转账备注（微信用户会收到该备注），UTF8编码，最多允许32个字符
                    'transfer_remark' => '提现至微信零钱',
                    //openid是微信用户在公众号appid下的唯一用户标识（appid不同，则获取到的openid就不同），可用于永久标记一个用户
                    'openid' => $userAuth['openid'],
                ]]
        ];
        if ($withdrawApply['left_money'] >= 2000) {
            if (empty($withdrawApply['real_name'])) {
                throw new \Exception('转账金额 >= 2000元，收款用户真实姓名必填');
            }
            $data['transfer_detail_list'][0]['user_name'] = $this->getEncrypt($withdrawApply['real_name'],$config);
        }
        $token  = $this->tokens($url,$http_method,$data,$config);//获取token
        $result = $this->https_request($url,json_encode($data),$token);//发送请求
        $result_arr = json_decode($result,true);
        if(!isset($result_arr['create_time'])) {//批次受理失败
            return ['code'=>201,'msg'=>$result_arr['message']];
        }
        //批次受理成功，进行操作
        return ['code'=>200,'msg'=>''];
    }

    /**
     * @notes 获取签名
     */
    function tokens($url,$http_method,$data,$config)
    {
        $timestamp   = time();//请求时间戳
        $url_parts   = parse_url($url);//获取请求的绝对URL
        $nonce       = $timestamp.rand('10000','99999');//请求随机串
        $body        = empty($data) ? '' : json_encode((object)$data);//请求报文主体
        $stream_opts = [
            "ssl" => [
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ]
        ];

//        $apiclient_cert_arr = openssl_x509_parse(file_get_contents($config['cert_path'],false, stream_context_create($stream_opts)));
        $apiclient_cert_arr = openssl_x509_parse(file_get_contents(getcwd().'/apiclient_cert.pem',false, stream_context_create($stream_opts)));
        $serial_no          = $apiclient_cert_arr['serialNumberHex'];//证书序列号
//        $mch_private_key    = file_get_contents($config['key_path'],false, stream_context_create($stream_opts));//密钥
        $mch_private_key    = file_get_contents(getcwd().'/apiclient_key.pem',false, stream_context_create($stream_opts));//密钥
        $merchant_id = $config['mch_id'];//商户id
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
        $message = $http_method."\n".
            $canonical_url."\n".
            $timestamp."\n".
            $nonce."\n".
            $body."\n";
        openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
        $sign = base64_encode($raw_sign);//签名
        $schema = 'WECHATPAY2-SHA256-RSA2048';
        $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
        return $schema.' '.$token;
    }

    /**
     * @notes 发送请求
     */
    function https_request($url,$data,$token)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, (string)$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //添加请求头
        $headers = [
            'Authorization:'.$token,
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        if(!empty($headers)){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * @notes 敏感信息加解密
     */
    function getEncrypt($str,$config)
    {
        //$str是待加密字符串
//        $public_key = file_get_contents($config['cert_path']);
        $public_key = file_get_contents(getcwd().'/apiclient_cert.pem');
        $encrypted = '';
        if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
            //base64编码
            $sign = base64_encode($encrypted);
        } else {
            throw new \Exception('encrypt failed');
        }
        return $sign;
    }

    /**
     * @notes 商家明细单号查询
     */
    function detailsQuery($withdrawApply,$config)
    {
        //请求URL
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches/out-batch-no/'.$withdrawApply['batch_no'].'/details/out-detail-no/'.$withdrawApply['sn'];
        //请求方式
        $http_method = 'GET';
        //请求参数
        $data = [];
        $token  = $this->tokens($url,$http_method,$data,$config);//获取token
        $result = $this->https_request($url,$data,$token);//发送请求
        $result_arr = json_decode($result,true);
        return $result_arr;
    }


}
